<?php

/**
 * 后台文章模块 Model
 * ============================================================================
 * TBlog TBlog博客系统　BY Tmac PHP MVC framework
 * $Author: zwt007 $  <zwttmac@qq.com>
 * $Id: article.class.php 31 2011-07-11 15:25:51Z zwt007 $
 * http://www.t-mac.org；
 */
class article extends Model
{

    private $class_table;
    private $article_table;
    private $addonarticle_table;
    private $city_table;

    /**
     * 初始化变量　定义私有变量
     */
    public function _init()
    {
        //连接数据库
        $this->connect();
        $this->class_table = '#@__category';
        $this->article_table = '#@__article';
        $this->addonarticle_table = '#@__addonarticle';
        $this->city_table = '#@__city';
    }

    /**
     * 保存
     * @param string $menusMain
     * return Boole
     */
    public function addArticle($table, $info, $mode = 'INSERT', $where = '')
    {
        if ($table == 'article') {
            $table = $this->article_table;
        } else {
            $table = $this->addonarticle_table;
        }
        $rs = $this->db->autoExecute($table, $info, $mode, $where);
        return $rs;
    }

    /**
     * 保存返回article_id
     * @param string $menusMain
     * return Boole
     */
    public function addArticleReturn($info)
    {
        $rs = $this->db->autoInsertReturn($this->article_table, $info);
        return $rs;
    }

    /**
     * 获取一个资讯栏目信息
     * @param int $class_id 栏目id
     * return array
     */
    public function getArticleInfo($aid)
    {
        $rs = $this->db->getRow("SELECT a.*, b.content FROM $this->article_table a LEFT JOIN $this->addonarticle_table b ON a.article_id = b.article_id WHERE a.article_id = '$aid' LIMIT 0,1");
        return $rs;
    }

    /**
     * 获取资讯栏目
     * return article_class,pages
     */
    public function getClass($type = '')
    {
        if (!empty($type)) {
            $where = " WHERE channeltype='$type'";
        } else {
            $where = '';
        }
        $sql = "SELECT * FROM {$this->class_table}{$where} ORDER BY cat_order DESC, cat_id DESC";
        $rs = $this->db->getAll($sql);
        return $rs;
    }

    /**
     * 获取所有资讯
     * return article_class,pages
     */
    public function getArticleList($channelid, $uid=1, $url = null, $cat_id = null)
    {
        $where = " WHERE type='post'";
        if ($url == '')
            $url = PHP_SELF . '?m=article';
        if (!empty($cat_id)) {            
            $cat_ids = $this->M('category')->getSonTreeList($cat_id, $uid);            
            $where .= " AND cat_id IN($cat_ids)";
            $url .= "&cat_id=$cat_id";
        }
        if (!empty($channelid)) {
            $where .= " AND channel = '$channelid'";
            $url .= "&channelid=$channelid";
        }
        if ($uid > 1) {
            $where .= " AND uid = $uid";
        }
        $url .= '&page=';
        $count = $this->db->getOne("SELECT COUNT(*) FROM $this->article_table {$where}");

        $pages = $this->P('Pages');
        $pages->setTotal($count);
        $pages->setUrl($url);
        $pages->setPrepage(20);
        $limit = $pages->getSqlLimit();
        $sql = "SELECT article_id, cat_id, title, time, click_count FROM {$this->article_table}{$where} ORDER BY article_id DESC LIMIT $limit";
        $rs = $this->db->getAll($sql);
        //取所有的资讯栏目 不用LEFT JOIN取class_name
        $rs_class = $this->getClass();
        $channeltype = Tmac::config('channel.channeltype');
        $ary_class = array();

        foreach ($rs_class AS $kk => $vv) {
            $ary_class['cat_name'][$vv['cat_id']] = $vv['cat_name'];
            $ary_class['channeltype'][$vv['cat_id']] = $channeltype[$vv['channeltype']];
            $ary_class['channelid'][$vv['cat_id']] = $vv['channeltype'];
        }

        //遍历通过class_id取class_name
        if (is_array($rs)) {
            foreach ($rs AS $k => $v) {
                $rs[$k]['cat_name'] = $ary_class['cat_name'][$v['cat_id']];
                $rs[$k]['time'] = date('Y/m/d H:i:s', $v['time']);
                $rs[$k]['channeltype'] = $ary_class['channeltype'][$v['cat_id']];
                $rs[$k]['channelid'] = $ary_class['channelid'][$v['cat_id']];
            }
        }

        $type = empty($cat_type) ? 'article' : $cat_type;
        //把文章的当前page写到cookies里
        HttpResponse::setCookie($type . '_page', $pages->getNowPage());

        $ErrorMsg = '';
        if ($count == 0) {
            $ErrorMsg = "暂无资讯文章!";
        }

        $this->assign('rs', $rs);
        $this->assign('pageCurrent', $pages->getNowPage());
        $this->assign('page', $pages->show());
        $this->assign('ErrorMsg', $ErrorMsg);
        return $rs;
    }

    /**
     * 取省列表 或根据省id取城市列表
     * @param <type> $type  默认c取city列表 p取province列表
     * @param <int>  $pid   省级id
     * @return array
     */
    public function getCity($type = 'c', $pid = null)
    {
        if ($type == 'p') {
            $rs = $this->db->getAll("SELECT Pid, Pname, suoxie FROM $this->city_table WHERE province = 1");
        } else {
            $rs = $this->db->cacheGetAll("SELECT cityid, cityname, suoxie FROM $this->city_table WHERE pid = $pid ORDER BY province DESC, abcd ASC");
        }
        return $rs;
    }

    /**
     * del
     * @param int $class_id
     */
    public function delArticle($id)
    {
        $rs = $this->db->execute("DELETE FROM $this->article_table WHERE article_id in ($id)");
        $rs = $this->db->execute("DELETE FROM $this->addonarticle_table WHERE article_id in ($id)");
        return $rs;
    }

    /**
     * 递归获取分类数组
     *
     * @param int $reid			    父级id
     * @param int $level			级别
     * @param int $current_id		当前编辑的分类id
     * @param int $tabel			要查询sql table
     * @param int $where			要查询sql where
     */
    public function article_cat_tree($reid, $level, $current_id, $channelid, $table="#@__category")
    {
        global $el; //定义全局变量 返回值
        $prefix_space = "";
        for ($i = 0; $i < $level; $i++) {
            $prefix_space .= "　"; //第一级就增加一个缩进
        }
        $sqltree = "SELECT cat_id, cat_pid, cat_name FROM " . $table . " WHERE cat_pid = " . $reid . " ORDER BY cat_order DESC";
        $rs = $this->db->getAll($sqltree);
        if (is_array($rs)) {
            foreach ($rs as $k => $v) {
                if ($v['cat_id'] == $current_id) {
                    $select = " selected";
                } else {
                    $select = "";
                }
                $el .= '<option value="' . $v['cat_id'] . '" ' . $select . '>' . $prefix_space . '|-' . $v['cat_name'] . '</option><br>';
                //echo "<option value=".$v['id'].$select.">".$prefix_space."|-".$v['typename'].$v[id]."</option><br>";
                $this->article_cat_tree($v['cat_id'], $level + 1, $current_id, $channelid, $table); //存在下一级就再次递归调用函数
            }
        }
        return $el; //最后返回树形菜单
    }

    /**
     * 判断用户对此文章是否有操作权限
     * @param <type> $id
     * @param <type> $uid
     * @return <type>
     */
    public function checkUserArticle($id, $uid)
    {
        $info = $this->getArticleInfo($id);
        if ($info['uid'] == $uid || $uid == 1) {
            return true;
        } else {
            $this->redirect('仅限操作自己的文章权限');
            exit;
        }
    }

}